const Path = require('path');
const fs = require('fs')
const { app, dialog } = require('electron')
const indexHtml = Path.join(__dirname, "../render/index/index.html")

//系统插件路径
const plugins = {
    primary: [],
    render: [],
}

const init = () => {
    // console.log("windows.js  process.cwd", process.cwd())

    //加载plugins
    {
        // const pluginDir = Path.join(process.cwd(), "../plugins") //@TODO打包时
        const pluginDir = Path.join(process.cwd(), "/plugins") //调试时

        if (!fs.existsSync(pluginDir) || !fs.statSync(pluginDir).isDirectory()) {
            return;
        }

        fs.readdirSync(pluginDir).forEach(dirname => {
            let dirPath = Path.join(pluginDir, dirname)

            if (!fs.statSync(dirPath).isDirectory()) {
                //非目录退出
                return;
            }

            if (dirname.match(/[\u4e00-\u9fa5]/g) != null) {
                //不能以中文命名
                return;
            }

            let jsonPath = Path.join(dirPath, "package.json");
            if (!fs.existsSync(jsonPath)) {
                //没有package.json退出
                return;
            }

            let json = fs.readFileSync(jsonPath, "utf-8");
            let pack = JSON.parse(json);

            let map = {
                key: dirname,
                path: dirPath,
                priority: 10,
            }

            if (typeof pack.priority == "number") {
                map.priority = pack.priority; //设置优先级
            }

            if (pack.render) {
                plugins.render.push(map) //如果有render标记 加入render组
            }

            if (pack.primary) {
                plugins.primary.push(map)   //如果有primary标记 加入primary组
            }
        })


        plugins.primary.sort((a, b) => {
            return a.priority - b.priority
        })

        plugins.render.sort((a, b) => {
            return a.priority - b.priority
        })
    }
}

const windows = {
    startup: null, //启动界面
    main: null,    //主界面
    tray: null,    //托盘

    initStepCount: [], //记录正在初始化的service 有异步操作的才需要

    setInitModule(name) {
        if (windows.initStepCount.indexOf(name) != -1) {
            // console.log("重复注册了初始化模块!", name);
            return
        }

        windows.initStepCount.push(name);
    },


    setInitModuleSuccess(name) {
        let index = windows.initStepCount.indexOf(name)

        if (index == -1) {
            console.log("没有注册该初始化模块!", name)
            return
        }
        windows.initStepCount.splice(index, 1);
    },


    showMain() {
        let delay = 4000;
        let intv = setInterval(() => {
            if (windows.initStepCount.length <= 0) {
                clearInterval(intv);
                windows.startup.destroy();
                windows.main.loadFile(indexHtml);
                windows.main.show();
                windows.initStepCount = null;

                //@TEST
                windows.main.webContents.openDevTools()
                // windows.main.minimize();
            } else {
                delay -= 2000;

                if (delay <= 0) {
                    clearInterval(intv);
                    dialog.showMessageBox({
                        type: 'error',
                        title: 'dnf-app启动超时',
                        message: `模块初始化超时,未完成初始化的模块:${windows.initStepCount.join(",")}`,
                        buttons: ['确定']
                    }).then(resp => {
                        app.quit();
                    })
                } else {
                    console.log("等待模块初始化:", windows.initStepCount)
                }
            }
        }, 2000);
    },

    //获取插件和路径
    //@param type:string "render" "primary"
    getPlugins(type) {
        return plugins[type];
    },


}

init();
global.windows = windows;
global.Sqlite3 = require("sqlite3");
global.Jimp = require("jimp");
global.encoding =  require('encoding');
module.exports = windows